﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ControlCenter.Model;
using ControlCenter.Model.WebApiDto;
using Dapper;

namespace ControlCenter.Data
{
    /// <summary>
    /// 执行队列仓储类
    /// </summary>
    public class ExecutionQueueRepository : RepositoryBase, IExecutionQueueRepository
    {

        #region CRUD
        private const string UpdateOrSaveSql = @"
IF not exists (select * from ExecutionQueue where ExecutionQueueId=@ExecutionQueueId)
BEGIN
  INSERT INTO [dbo].[ExecutionQueue]
           ([ExecutionQueueId]
            ,[RpId]
           ,[RobotId]
           ,[PackageId]
		   ,[Type]
           ,[ExecutionDate]
           ,[ExecutionTime]
           ,[Status]
           ,[Message]
           ,[TraceId])
     VALUES
           (@ExecutionQueueId
            ,@RpId
           ,@RobotId
           ,@PackageId
		   ,@Type
           ,@ExecutionDate
           ,@ExecutionTime
           ,@Status
           ,@Message
           ,@TraceId)
END
ELSE
BEGIN
 UPDATE [dbo].[ExecutionQueue]
   SET 
      [ExecutionDate] = @ExecutionDate
      ,[ExecutionTime] = @ExecutionTime
      ,[Status] = @Status
      ,[Message] = @Message
 WHERE [ExecutionQueueId] = @ExecutionQueueId
END
";

        #endregion

        /// <summary>
        /// 更新执行状态
        /// </summary>
        /// <param name="executionQueue"></param>
        /// <returns></returns>
        public async Task<bool> UpdateExecutionStatus(ExecutionQueue executionQueue)
        {
            return (await ControlCenterDbConn.ExecuteAsync(UpdateOrSaveSql, executionQueue)) > 0;
        }

        /// <summary>
        /// 查询任务日志，返回分页数据
        /// </summary>
        /// <param name="robotId"></param>
        /// <param name="rpId"></param>
        /// <param name="startRows"></param>
        /// <param name="endRows"></param>
        /// <returns></returns>
        public async Task<PagedData<LogQueryReturnDto>> QueryTaskLog(Guid? robotId, Guid? rpId, int startRows, int endRows)
        {
            string sqlWhere = " eq.[Type]=1 ";
            if (robotId.HasValue && robotId != Guid.Empty)
            {
                sqlWhere += " AND eq.RobotId=@RobotId ";
            }
            if (rpId.HasValue && rpId != Guid.Empty)
            {
                sqlWhere += " AND eq.RpId=@RpId ";
            }

            string countSql = @"SELECT COUNT(1) FROM dbo.ExecutionQueue AS eq
	LEFT JOIN dbo.ProjectPackageInfo AS p ON p.PackageId=eq.PackageId WHERE " + sqlWhere;
            string sql = @"
SELECT * FROM(
SELECT ROW_NUMBER() OVER(ORDER BY ExecutionDate Desc) RowNo,eq.*,p.ProjectName AS PackageName FROM dbo.ExecutionQueue AS eq
	LEFT JOIN dbo.ProjectPackageInfo AS p ON p.PackageId=eq.PackageId
WHERE " + sqlWhere + @"
)T1 WHERE RowNo>=@StartRows AND RowNo <=@EndRows";

            var pagedData = new PagedData<LogQueryReturnDto>();
            pagedData.TotalCount = await ControlCenterDbConn.ExecuteScalarAsync<int>(countSql, new { RobotId = robotId, RpId = rpId });
            var list = await ControlCenterDbConn.QueryAsync<LogQueryReturnDto>(sql,
                new { RobotId = robotId, RpId = rpId, StartRows = startRows, EndRows = endRows});
            pagedData.Data = list.ToList();

            return pagedData;
        }

        /// <summary>
        /// 查询任务跟踪明细日志，返回分页数据
        /// </summary>
        /// <param name="traceId"></param>
        /// <param name="startRows"></param>
        /// <param name="endRows"></param>
        /// <returns></returns>
        public async Task<PagedData<LogQueryReturnDto>> QueryTraceLog(Guid traceId, int startRows, int endRows)
        {
            string countSql = @"SELECT COUNT(1) FROM dbo.ExecutionQueue WHERE TraceId=@traceId AND [Type]=2";
            string sql = @"
SELECT * FROM(
SELECT ROW_NUMBER() OVER(ORDER BY ExecutionDate Desc) RowNo,eq.*,p.ProjectName AS PackageName FROM dbo.ExecutionQueue AS eq
	LEFT JOIN dbo.ProjectPackageInfo AS p ON p.PackageId=eq.PackageId
WHERE TraceId=@traceId AND [Type]=2
)T1 WHERE RowNo>=@StartRows AND RowNo <=@EndRows";

            var pagedData = new PagedData<LogQueryReturnDto>();
            pagedData.TotalCount = await ControlCenterDbConn.ExecuteScalarAsync<int>(countSql, new {TraceId=traceId});
            var list = await ControlCenterDbConn.QueryAsync<LogQueryReturnDto>(sql,
                new { TraceId = traceId, StartRows = startRows, EndRows = endRows });
            pagedData.Data = list.ToList();

            return pagedData;
        }
    }
}
